import logging

import requests

from kumquat_king_pyside6.app_config import KUMQUAT_KING_URL
from kumquat_king_pyside6.tools import handle_orders_df


def handle_requests(response):
    try:
        response.raise_for_status()
        logging.info(f'Response : {response.json()}')
        return response.status_code, response.json()
    except requests.exceptions.HTTPError as err:
        logging.error(f'HTTP error occurred: {err}')
        return None


def get_kumquat_format():
    getKumquatFormatURL = f'{KUMQUAT_KING_URL}/kumquat/format'
    headers = {
        "Content-Type": "application/json",
    }
    response = requests.get(getKumquatFormatURL, headers=headers)
    return handle_requests(response)


def get_presenters():
    getPresentersURL = f'{KUMQUAT_KING_URL}/customer/presenter'
    headers = {
        "Content-Type": "application/json",
    }
    response = requests.get(getPresentersURL, headers=headers)
    return handle_requests(response)


def get_kumquats():
    getAllKumquatsURL = f'{KUMQUAT_KING_URL}/kumquat/all'
    headers = {
        "Content-Type": "application/json",
    }
    response = requests.get(getAllKumquatsURL, headers=headers)
    return handle_requests(response)


def create_kumquat(kumquatJson):
    createKumquatURL = f'{KUMQUAT_KING_URL}/kumquat'
    headers = {
        "Content-Type": "application/json",
    }
    response = requests.post(createKumquatURL, data=kumquatJson, headers=headers)
    return handle_requests(response)


def get_orders_by_filter(filters):
    getOrdersByFilterURL = f'{KUMQUAT_KING_URL}/order/filter'
    headers = {
        "Content-Type": "application/json",
    }
    """
    {
      "customer_name": "",
      "customer_presenter": "",
      "kumquat_name": "",
      "kumquat_style": "",
      "start_date": "2024-11-30",
      "end_date": "2024-12-01",
      "status": "",
      "note": ""
    }
    """
    logging.info(f"Request orders with filters: {filters}")
    response = requests.post(getOrdersByFilterURL, data=filters, headers=headers)
    handlers = handle_requests(response)
    return handlers


def bulk_create_orders(ordersJson):
    ordersPayload, customersPayload = handle_orders_df(ordersJson)
    logging.info(f"Build json: {ordersPayload}")
    logging.info(f"Create Customer json {customersPayload}")
    bulkCreateCustomerUrl = f'{KUMQUAT_KING_URL}/customer/all'
    bulkCreateOrderUrl = f'{KUMQUAT_KING_URL}/order/all'
    headers = {
        "Content-Type": "application/json",
    }
    logging.info("Create customers firstly.")
    response = requests.post(bulkCreateCustomerUrl, data=customersPayload, headers=headers)
    handlers = handle_requests(response)
    if handlers[0] in [200, 201]:
        logging.info("Create customers successfully, then create the orders")
        response = requests.post(bulkCreateOrderUrl, data=ordersPayload, headers=headers)
        handlers = handle_requests(response)
        logging.info(f"Response for ORDER: {handlers[0]}")
        return handlers
    else:
        logging.error("Create customers failed, so unable to create the orders, please refer logs.")
        return handlers
